package com.sanri.tools.modules.mock.l7.websocket.chat.repository;

import com.sanri.tools.modules.core.service.file.FileManager;
import com.sanri.tools.modules.core.utils.NetUtil;
import com.sanri.tools.modules.core.utils.OnlyPath;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;

/**
 * 媒体数据
 * $datadir
 *   chat
 *     media
 */
@Repository
@Slf4j
public class MediaRepository {
    @Autowired
    private MessageRepository messageRepository;

    @Autowired
    private FileManager fileManager;

    @Value("${server.port:8080}")
    private int port;

    /**
     * 媒体数据存储
     * @param file
     * @throws IOException
     * @return
     */
    public String storageMedia(MultipartFile file) throws IOException {
        File dir = fileManager.mkDataDir("chat/media");
        File targetFile = new File(dir, file.getOriginalFilename());

        try (InputStream inputStream = file.getInputStream();
            final FileOutputStream fileOutputStream = new FileOutputStream(targetFile)){
            FileCopyUtils.copy(inputStream, fileOutputStream);
        }
        OnlyPath relativize = new OnlyPath(dir).relativize(new OnlyPath(targetFile));

        // 解析为网络地址
        List<String> localIPs = NetUtil.getLocalIPs();
        String host = localIPs.get(0);
        return "http://"+host+":"+port+"/chat/media/"+relativize.toString();
    }
}
